#include "video_decoder.h"
#include "include.h"
#include <QPainter>


video_decoder::video_decoder(QWidget *parent) :
    QWidget(parent)
{
    decoder = new CXvidDec() ;
    decoder->AttachCaller(IMAGE_WIDTH, IMAGE_HEIGHT, this) ;
    decoder->Open() ;
    refresh_timer=new QTimer();
    connect(refresh_timer,SIGNAL(timeout()),this,SLOT(refresh_timeout()));
    refresh_timer->start(900/FPS);
    rtprecthread.start();
    //read_video_stream("/host/13:48:40");
}

video_decoder::~video_decoder()
{
    delete refresh_timer;
    delete decoder;
    delete video_file;

}

void video_decoder::PostDecHandler(unsigned char * image, int used_bytes)
{
    outstream=image;
    //instream.remove(0,used_bytes);


}


void video_decoder::paintEvent(QPaintEvent *event )
{

    QImage frame(outstream,IMAGE_WIDTH,IMAGE_HEIGHT,QImage::Format_RGB888);
    QPainter widget_painter(this);
    widget_painter.drawImage(rect(), frame);

    if(!lock)
    {
    lock=true;
    instream+=rtprecthread.recbytes;
    rtprecthread.recbytes.resize(0);
    lock=false;
    }
    ret=decoder->Decode((uchar*)instream.data(),instream.size());
    widget_painter.setPen(QColor(255,0,0));
    widget_painter.drawText(100,150,QString::number(instream.size()));
    instream.remove(0,ret);

}

int video_decoder::read_video_stream(QString filename)
{
    video_file=new QFile(filename);
    video_file->open(QIODevice::ReadOnly);
    instream=video_file->readAll();
   // decoder->Decode((uchar*)instream.data(),instream.size());

}


void video_decoder::refresh_timeout()
{

    update();

}
